package com.sakura.educms.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sakura.educms.entity.CrmBanner;
import com.sakura.educms.mapper.CrmBannerMapper;
import com.sakura.educms.service.CrmBannerService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 首页banner表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-03-07
 */
@Service
public class CrmBannerServiceImpl extends ServiceImpl<CrmBannerMapper, CrmBanner> implements CrmBannerService {


    @Autowired
    private StringRedisTemplate template;

    final String BannerKey = "BannerList";

    /**
     * 查询所有banner
     */
    @Override
    public List<CrmBanner> selectAllBanner() {
        List<CrmBanner> list = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        if (template.hasKey(BannerKey)){
            //如果redis中有该数据则直接从里面读取
            String bannerStr = template.opsForValue().get(BannerKey);
            JavaType javaType = mapper.getTypeFactory()
                    .constructParametricType(ArrayList.class, CrmBanner.class);
            try {
                list = mapper.readValue(bannerStr,javaType);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return list;
            }
        }else{
            //根据id进行降序排列，显示排列之后前两条记录
            QueryWrapper<CrmBanner> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("id");
            //last方法，拼接sql语句
            wrapper.last("limit 2");
            list = baseMapper.selectList(null);
            //同时将list存入redis中
            String jsonString = null;
            try {
                jsonString = mapper.writeValueAsString(list);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            template.opsForValue().set(BannerKey,jsonString);
        }
        return list;
    }


}
